package pers.jing.android.helper.widget

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import pers.jing.android.helper.DeviceManager
import pers.jing.android.helper.model.CODE_SUCCESS
import pers.jing.android.helper.model.CommandResult
import pers.jing.android.helper.model.DeviceInfo
import pers.jing.android.helper.page.BaseViewModel

/**
 * 安装APK弹窗的ViewModel
 */
class InstallApkViewModel(val deviceManager: DeviceManager): BaseViewModel() {


    init {
        viewModelScope.launch(Dispatchers.IO) {
            deviceManager.loadDevices()
        }
    }


    fun getStateFlowDevices(): StateFlow<List<DeviceInfo>> {
        return deviceManager.getStateFlowDevices()
    }


    fun install(index: Int, apkPath: String) {
        viewModelScope.launch(Dispatchers.IO) {
            showProgressDialog("正在安装")
            val devices = deviceManager.getDevices();
            val cResult = if (index >= 0 && index < devices.size) {
                deviceManager.install(devices[index].serialId, apkPath)
            } else {
                CommandResult(-1, error = listOf("暂无可用设备"))
            }
            closeProgressDialog()
            if (CODE_SUCCESS == cResult.code) {
                //安装成功
                showConfirmDialog("安装成功", nextStep = "closeInstallApkDialog")
            } else {
                //安装失败
                val msg = cResult.error?.joinToString("\n")
                showConfirmDialog("安装失败: $msg", nextStep = "none")
            }
        }
    }

}